// import store from '../store'
// import { getDetail } from "@/apiOptions/home_api.js";
// import dictMgr from '@/biz/building/dict.js'
// import buildMgr from '@/biz/building'
// import userMgr from '@/biz/user'

Function.prototype.method = function(name, fn) {
  this.prototype[name] = fn;
  return this;
};

Array.prototype.remove = function(item) {
  let idx = this.indexOf(item);
  if (idx > -1) {
    this.splice(idx, 1);
  }
};

if (!String.prototype.trim) {
  String.method("trim", function() {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
  });
}
var isType = function(type) {
  return function(obj) {
    return Object.prototype.toString.call(obj) == "[object " + type + "]";
  };
};
var isArray = isType("Array");
var isStr = isType("String");
var isObject = isType("Object");
var isFun = isType("Function");
var isRegExp = isType("RegExp");
const TOOL = {
  isArray: isArray,
  isStr: isStr,
  isObject: isObject,
  isFun: isFun,
  isRegExp: isRegExp,
  extend: function() {
    var options,
      copyIsArray,
      target = arguments[0] || {},
      i = 1,
      length = arguments.length,
      deep = false;

    if (typeof target === "boolean") {
      deep = target;
      target = arguments[i] || {};
      i++;
    }
    if (i === length) {
      target = this;
      i--;
    }
    for (; i < length; i++) {
      if ((options = arguments[i]) != null) {
        for (let name in options) {
          let clone,
            src = target[name],
            copy = options[name];
          if (target === copy) continue;
          if (
            deep &&
            copy &&
            (isObject(copy) || (copyIsArray = isArray(copy)))
          ) {
            if (copyIsArray) {
              copyIsArray = false;
              clone = src && isArray(src) ? src : [];
            } else {
              clone = src && isObject(src) ? src : {};
            }
            target[name] = this.extend(deep, clone, copy);
          } else if (copy !== undefined) {
            target[name] = copy;
          }
        }
      }
    }
    return target;
  },

  // openLoading() {
  //   store.dispatch('saveIsLoading', true)
  // },
  // closeLoading() {
  //   store.dispatch('saveIsLoading', false)
  // },

  getStorage(item) {
    // 临时加
    // if (item == 'dictionaryData') {
    //   return JSON.stringify(dictMgr.info())
    // } else if (item == 'X-Token') {
    //   return userMgr.info() ? userMgr.info().token : ''
    // } else if (item == 'userMess') {
    //   return JSON.stringify(userMgr.info())
    // } else if (item == 'appId') {
    //   return 36
    // } else if (item == 'buildMess') {
    //   return JSON.stringify(buildMgr.info())
    // }

    var value = window.sessionStorage.getItem(item);
    if (value) {
      value = value;
      if (value.indexOf("time") > -1) value = JSON.parse(value);
      if (value.time && value.expires) {
        //设置了过期时间
        let newTime = new Date().valueOf(),
          oldTime = value.time;
        if (newTime - oldTime > value.expires) {
          window.sessionStorage.removeItem(item);
          value = "";
        } else {
          value = value.value ? value.value : value;
        }
      }
    }
    return value;
  },
  setStorage(obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        window.sessionStorage.setItem(key, String(obj[key]));
      }
    }
  },
  clearStorage(mess) {
    if (mess) {
      mess.forEach(item => {
        window.sessionStorage.removeItem(item);
      });
    } else {
      window.sessionStorage.clear();
    }
  },
  loadPageVar(sVar) {
    return decodeURI(
      window.location.search.replace(
        new RegExp(
          "^(?:.*[&\\?]" +
            encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") +
            "(?:\\=([^&]*))?)?.*$",
          "i"
        ),
        "$1"
      )
    );
  },

  getlocalStorage(item) {
    var value;
    value = window.localStorage.getItem(item);
    return value ? value : "";
  },
  setlocalStorage(obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        window.localStorage.setItem(key, String(obj[key]));
      }
    }
  },
  clearlocalStorage() {
    function clearCookie() {
      var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
      if (keys) {
        for (var i = keys.length; i--; )
          document.cookie = keys[i] + "=0;expires=" + new Date(0).toUTCString();
      }
    }

    if (window.localStorage) {
      window.localStorage.clear();
    } else {
      clearCookie();
    }
    // return this;
  },
  encrypt(value) {
    var encryptValue = "";
    var mask;
    var maskValue;
    for (var i = 0, len = value.length; i < len; i++) {
      mask = Math.round(Math.random() * 111) + 77;
      maskValue = value.charCodeAt(i) + mask;
      mask += i;
      encryptValue += String.fromCharCode(maskValue, mask);
    }
    return encryptValue;
  },
  decrypt(value) {
    var decryptValue = "";
    var k = 0;
    var v;
    var m;
    var decrypt = function(v, m, i) {
      v = v.charCodeAt(0);
      m = m.charCodeAt(0);
      m -= i;
      v -= m;
      return String.fromCharCode(v);
    };
    for (var i = 0, len = value.length; i < len; i++) {
      if (!(i % 2)) {
        v = value[i];
      } else {
        m = value[i];
        decryptValue += decrypt(v, m, k);
        k++;
      }
    }
    return decryptValue;
  },
  getToken() {
    return this.getStorage("X-Token") || "";
  },
  getCookie: function(name) {
    var arr,
      reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
    else return null;
  },
  setCookie: function(name, value, day) {
    if (day !== 0) {
      //当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
      var expires = day * 24 * 60 * 60 * 1000;
      var date = new Date(+new Date() + expires);
      document.cookie =
        name + "=" + escape(value) + ";expires=" + date.toUTCString();
    } else {
      document.cookie = name + "=" + escape(value);
    }
  },
  delCookie: function(name) {
    this.setCookie(name, " ", -1);
  },
  copy: function(source) {
    let result = Array.isArray(source) ? [] : {};
    for (var key in source) {
      result[key] =
        source[key] != null && typeof source[key] === "object"
          ? this.copy(source[key])
          : source[key];
    }
    return result;
  },
  getTime: function(t) {
    if (!t) return new Date().getTime();
    return new Date(String(t).replace(/-/g, "/")).getTime();
  },
  dateFtt: function(fmt, date) {
    if (typeof date === "string" || typeof date === "number") {
      date.indexOf("-") > -1 && (date = date.replace(/\-/g, "/"));
      date = new Date(date);
    }
    var o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
    return fmt;
  },

  getUrlParams(name) {
    var url = "";
    if (window.location.search == "") {
      url = window.location.hash;
    } else {
      url = window.location.search;
    }

    // var url = window.location.search;
    // var url = window.location.hash;
    var n = url.indexOf("?");
    // if (url.indexOf('?') == 1) {
    //   return false;
    // }
    url = url.substr(n + 1);
    url = url.split("&");
    var name = name || "";
    var nameres;
    for (var i = 0; i < url.length; i++) {
      var info = url[i].split("=");
      var obj = {};
      obj[info[0]] = decodeURI(info[1]);
      url[i] = obj;
    }
    if (name) {
      for (var i = 0; i < url.length; i++) {
        for (const key in url[i]) {
          if (key == name) {
            nameres = url[i][key];
          }
        }
      }
    } else {
      nameres = url;
    }
    return nameres;
  },
  // 时间格式转换 2021-08-02 00:00:00 => 2021-08-02
  formatterDate(date, num = 10) {
    if (!date) return date;
    return date.slice(0, num);
  },
  //  数组扁平化
  flattenArr(arr) {
    return arr.reduce((result, item) => {
      return result.concat(
        item,
        Array.isArray(item.children) ? TOOL.flattenArr(item.children) : []
      );
    }, []);
  },
  //数组对象深拷贝
  deepClone: function(obj) {
    let objClone = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === "object") {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          //判断ojb子元素是否为对象，如果是，递归复制
          if (obj[key] && typeof obj[key] === "object") {
            objClone[key] = this.deepClone(obj[key]);
          } else {
            //如果不是，简单复制
            objClone[key] = obj[key];
          }
        }
      }
    }
    return objClone;
  },
  //数组对象合并 obj 查询条件  options 表头筛选
  mergeObject: function(obj, options) {
    for (var objKey in obj) {
      for (var optionKey in options) {
        if (objKey == optionKey) {
          obj[objKey] = options[optionKey];
        }
      }
    }
    return obj;
  },
  /**
   * 数组去重
   * @params arr 要去重的数组
   * @params pro 数组中对象的某个属性
   * @returns arr 去重后的数组
   */
  noRepeatObj: function(arr, pro) {
    var hash = {};
    arr = arr.reduce(function(item, next) {
      hash[next[pro]] ? "" : (hash[next[pro]] = true && item.push(next));
      return item;
    }, []);
    return arr;
  },
  //手机号隐藏四位
  repPhoneNum(val) {
    if (val) {
      return val.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    } else {
      return "-";
    }
  },

  // EXLCL
  isExcel(type, name, data) {
    const link = document.createElement("a");
    const blob = new Blob([data]);
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    link.setAttribute("download", `${name}.` + type);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  },

  getTimeRi(n) {
    //本周、上周
    var now = new Date();
    var year = now.getFullYear();
    //因为月份是从0开始的,所以获取这个月的月份数要加1才行
    var month = now.getMonth() + 1;
    var date = now.getDate(); //日期
    var day = now.getDay(); //星期
    // console.log(date);
    //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
    if (day !== 0) {
      n = n + (day - 1);
    } else {
      n = n + day;
    }
    if (day) {
      //这个判断是为了解决跨年的问题
      if (month > 1) {
        month = month;
      }
      //这个判断是为了解决跨年的问题,月份是从0开始的
      else {
        year = year - 1;
        month = 12;
      }
    }
    now.setDate(now.getDate() - n);

    year = now.getFullYear();
    month = now.getMonth() + 1;
    date = now.getDate();
    // console.log(n);
    let s =
      year +
      "-" +
      (month < 10 ? "0" + month : month) +
      "-" +
      (date < 10 ? "0" + date : date);
    return s;
  },

  getDayRi(day) {
    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth() + 1;
    var tDate = today.getDate();
    tMonth = tMonth < 10 ? "0" + tMonth : tMonth;
    tDate = tDate < 10 ? "0" + tDate : tDate;
    return tYear + "-" + tMonth + "-" + tDate;
  },

  getMonthStartAndEnd(AddMonthCount) {
    //起止日期数组
    var startStop = new Array();
    //获取当前时间
    var currentDate = new Date();
    var month = currentDate.getMonth() + AddMonthCount;
    if (month < 0) {
      var n = parseInt(-month / 12);
      month += n * 12;
      currentDate.setFullYear(currentDate.getFullYear() - n);
    }
    currentDate = new Date(currentDate.setMonth(month));
    //获得当前月份0-11
    var currentMonth = currentDate.getMonth();
    //获得当前年份4位年
    var currentYear = currentDate.getFullYear();
    //获得上一个月的第一天
    var currentMonthFirstDay = new Date(currentYear, currentMonth, 1);
    //获得上一月的最后一天
    var currentMonthLastDay = new Date(currentYear, currentMonth + 1, 0);
    //添加至数组
    startStop.push(this.formatDate(currentMonthFirstDay));
    startStop.push(this.formatDate(currentMonthLastDay));
    //返回
    return startStop;
  },
  formatDate(date) {
    var year = "";
    var month = "";
    var day = "";
    var now = date;
    year = "" + now.getFullYear();
    if (now.getMonth() + 1 < 10) {
      month = "0" + (now.getMonth() + 1);
    } else {
      month = "" + (now.getMonth() + 1);
    }
    if (now.getDate() < 10) {
      day = "0" + now.getDate();
    } else {
      day = "" + now.getDate();
    }
    return year + "-" + month + "-" + day;
  },

  timeSub(time) {
    return time.substring(0, time.length - 3);
  },
  // 当前月
  currentMonth() {
    var myDate = new Date();
    var tYear = myDate.getFullYear();
    var tMonth =
      myDate.getMonth() + 1 >= 10
        ? myDate.getMonth() + 1
        : "0" + (myDate.getMonth() + 1);
    const pre = tYear + "-" + tMonth + "-01";
    const cur = TOOL.formatDate(myDate);
    return [pre, cur];
  },
  // 当前周
  currentWeek() {
    var myDate = new Date();
    // var tYear = myDate.getFullYear();
    // var tMonth = (myDate.getMonth() + 1) >= 10 ? myDate.getMonth() + 1 : '0' + (myDate.getMonth() + 1);

    var day = myDate.getDay();
    var deltaDay;
    if (day == 0) {
      deltaDay = 6;
    } else {
      deltaDay = day - 1;
    }
    const pre = TOOL.formatDate(
      new Date(myDate.getTime() - deltaDay * 24 * 60 * 60 * 1000)
    );
    const cur = TOOL.formatDate(myDate);
    return [pre, cur];
  },
  // objIfNull(obj) { // 判断一个对象下是否有空属性
  //   for (const key in obj) {
  //     if (obj.hasOwnProperty(key)) {
  //       if (obj[key] === null || obj[key] === '') {
  //         return false;
  //       }
  //     }
  //   }
  // },

  isRepeat(arr) {
    var obj = {};

    for (var i in arr) {
      //存在重复值
      if (obj[arr[i]]) return true;

      obj[arr[i]] = true;
    }
    //不重复
    return false;
  },

  /**
   * @desc 函数防抖
   * @param func 函数
   * @param wait 延迟执行毫秒数
   * @param immediate true 表立即执行，false 表非立即执行
   */
  debounce(func, wait, immediate = false) {
    let timeout;

    return function() {
      let context = this;
      let args = arguments;

      if (timeout) clearTimeout(timeout);
      if (immediate) {
        var callNow = !timeout;
        timeout = setTimeout(() => {
          timeout = null;
        }, wait);
        if (callNow) func.apply(context, args);
      } else {
        timeout = setTimeout(function() {
          func.apply(context, args);
        }, wait);
      }
    };
  },
  /**
   * @desc 函数节流
   * @param func 函数
   * @param wait 延迟执行毫秒数
   * @param type 1 表时间戳版，2 表定时器版
   */
  throttle(func, wait, type) {
    if (type === 1) {
      let previous = 0;
    } else if (type === 2) {
      let timeout;
    }
    return function() {
      let context = this;
      let args = arguments;
      if (type === 1) {
        let now = Date.now();

        if (now - previous > wait) {
          func.apply(context, args);
          previous = now;
        }
      } else if (type === 2) {
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = null;
            func.apply(context, args);
          }, wait);
        }
      }
    };
  },
  /**
   * 特殊字符校验
   */
  unNormalReg(parmas) {
    var regEn = /[`~!@#$%^&*()_+<>?:"{}, .\/;'[\]]/im,
      regCn = /[·！#￥（——）：；“”‘、，| 《。》？、【】[\]]/im;
    return regEn.test(parmas) || regCn.test(parmas);
  },
  /**
   * 获取元素到顶部距离-通用方法
   *
   */
  getPositionTop(node) {
    if (node) {
      var top = node.offsetTop;
      var parent = node.offsetParent;
      while (parent != null) {
        top += parent.offsetTop;
        parent = parent.offsetParent;
      }
      return top;
    } else {
      return 0;
    }
  },
  /**
   *
   * @param {*} node 获取元素到左侧距离-通用方法
   * @returns
   */
  getPositionLeft(node) {
    var left = node.offsetLeft;
    var parent = node.offsetParent;
    while (parent != null) {
      left += parent.offsetLeft;
      parent = parent.offsetParent;
    }
    return left;
  },
  /**
   * 获取table高度
   * 40 表格头部的高度
   * 10 横向滚动条的高度
   * 60 分页的高度
   * 100 暂无数据高度处理
   * UVal  需要特别处理的情况  针对实际内容区的高度不以window.innerHeight为基准 如组织管理的边框
   */
  getTableHeight(node, UVal = 0) {
    let scrollWidth =
      node.$children[1].$el.clientWidth + TOOL.getPositionLeft(node.$el) >
      window.innerWidth
        ? 10
        : 0;
    let resizeHeight =
      node.$children[1].$el.clientHeight + 40 + scrollWidth >
      window.innerHeight - TOOL.getPositionTop(node.$el) - 60
        ? window.innerHeight - TOOL.getPositionTop(node.$el) - 60 - UVal
        : node.$children[1].$el.clientHeight + 40 + scrollWidth < 100
        ? 100
        : node.$children[1].$el.clientHeight + 40 + scrollWidth;
    return resizeHeight;
  },
  /**
   * 图片压缩
   * @param {文件} file
   * quality 压缩质量
   */
  compressImg(file, quality) {
    return new Promise((resolve, reject) => {
      var img = new Image();
      //获取原图的base64
      var reader = new FileReader();
      reader.onload = function(e) {
        img.src = e.target.result;
      };
      reader.readAsDataURL(file);

      img.onload = function() {
        // 当图片宽度超过 700px 时, 就压缩成 700px, 高度按比例计算 // 压缩质量可以根据实际情况调整
        var w = Math.min(700, img.width);
        var h = img.height * (w / img.width);
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = w;
        canvas.height = h;
        ctx.drawImage(img, 0, 0, w, h);
        //将canvas转成base64第二个参数是设置质量（越大越好最大1）
        let newFile = TOOL.base64UrlToBlob(
          canvas.toDataURL("image/jpg", quality),
          file.name
        );
        resolve(newFile);
      };
    });
  },
  /*这里转blob 转file*/
  base64UrlToBlob(urlData, name) {
    let arr = urlData.split(","),
      mime = arr[0].match(/:(.*?);/)[1], // 去掉url的头，并转化为byte
      bstr = atob(arr[1]), // 处理异常,将ascii码小于0的转换为大于0
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    //转file
    return new File([u8arr], name, {
      type: mime
    });
    // 转Blob
    // return new Blob([u8arr], { type: mime, name: name, lastModified: Date.now() });
  },

  // 判断日期差
  dateDiff(d1, d2) {
    d1 = new Date(d1.replace(/-/g, "/"));
    d2 = new Date(d2.replace(/-/g, "/"));
    var obj = {},
      M1 = d1.getMonth(),
      D1 = d1.getDate(),
      M2 = d2.getMonth(),
      D2 = d2.getDate();
    obj.Y =
      d2.getFullYear() -
      d1.getFullYear() +
      (M1 * 100 + D1 > M2 * 100 + D2 ? -1 : 0);
    obj.M = (obj.Y > 0 ? obj.Y * 12 : 12) + M2 - M1 + (D1 > D2 ? -1 : 0);
    obj.s = Math.floor((d2 - d1) / 1000); //差几秒
    obj.m = Math.floor(obj.s / 60); //差几分钟
    obj.h = Math.floor(obj.m / 60); //差几小时
    obj.D = Math.floor(obj.h / 24); //差几天
    return obj;
  },

  // 空数据转换成-
  transformationNull(obj) {
    Object.keys(obj).map(function(key) {
      (obj[key] == null || obj[key] === "") && (obj[key] = "-"); //比较key
    });
  },
  // 接口传参-换成null
  transformationNullSet(obj) {
    Object.keys(obj).map(function(key) {
      obj[key] == "-" && (obj[key] = null); //比较key
    });
  },

  //   金额转换成三位分割法
  formatterMoney(val) {
    return val != "-" && val != undefined
      ? Number(val)
          .toLocaleString()
          .includes(".")
        ? Number(val).toLocaleString()
        : Number(val).toLocaleString() + ".00"
      : "-";
  },
  // 将数字转化为千分位，三位以逗号隔开
  formatNumtoLocaleString: function(num) {
    if (num) {
      return parseFloat(num).toLocaleString();
    }
    return num;
  }
};
export default TOOL;

//手机号隐藏中间4位

// export const WB = new wb(["router", "progress"]);
